﻿namespace ModulesToolkit.Web.Membership
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.UI.WebControls;
    using Microsoft.Practices.ObjectBuilder;
    using Microsoft.Practices.Web.UI.WebControls;
    using ModulesToolkit.DataContracts;
    using ModulesToolkit.DataContracts.Membership;
    using ModulesToolkit.Membership.Views;

    public partial class GroupsList : Microsoft.Practices.CompositeWeb.Web.UI.Page, IGroupsListView
    {
        #region Fields

        private GroupsListPresenter _presenter;

        private GroupMemberDtoSearchCriteria _groupMemberSearchCriteria;
        private GroupDtoSearchCriteria _searchCriteria;
        private MemberDtoSearchCriteria _memberSearchCriteria;
        protected RolesSearchCriteria _rolesSearchCriteria;

        #endregion Fields

        #region Properties

        [CreateNew]
        public GroupsListPresenter Presenter
        {
            get
            {
                return this._presenter;
            }
            set
            {
                if (value == null)
                    throw new ArgumentNullException("value");

                this._presenter = value;
                this._presenter.View = this;
            }
        }

        #endregion Properties

        #region IGroupsListView Members

        #region Properties

        public GroupDtoSearchCriteria SearchCriteria
        {
            get
            {
                if (_searchCriteria == null)
                    _searchCriteria = new GroupDtoSearchCriteria();
                _searchCriteria.Name = this.uxName.Text;
                _searchCriteria.PageNumber = this.uxGroupsList.PageIndex + 1;
                _searchCriteria.PageSize = this.uxGroupsList.PageSize;
                return _searchCriteria;
            }
        }
        public MemberDtoSearchCriteria MembersSearchCriteria
        {
            get
            {
                if (this._memberSearchCriteria == null)
                    this._memberSearchCriteria = new MemberDtoSearchCriteria();
                this._memberSearchCriteria.PageNumber = this.uxMembersList.PageIndex + 1;
                this._memberSearchCriteria.PageSize = this.uxMembersList.PageSize;
                return this._memberSearchCriteria;
            }
        }
        public GroupMemberDtoSearchCriteria GroupMembersSearchCriteria
        {
            get
            {
                if (this._groupMemberSearchCriteria == null)
                    this._groupMemberSearchCriteria = new GroupMemberDtoSearchCriteria();
                this._groupMemberSearchCriteria.GroupId = this.EditingId;
                this._groupMemberSearchCriteria.PageNumber = this.uxGroupMembersList.PageIndex + 1;
                this._groupMemberSearchCriteria.PageSize = this.uxGroupMembersList.PageSize;
                return this._groupMemberSearchCriteria;
            }
        }
        public RolesSearchCriteria RolesSearchCriteria
        {
            get
            {
                if (this._rolesSearchCriteria == null)
                    this._rolesSearchCriteria = new RolesSearchCriteria();
                this._rolesSearchCriteria.PageNumber = this.uxRolesList.PageIndex + 1;
                this._rolesSearchCriteria.PageSize = this.uxRolesList.PageSize;
                return _rolesSearchCriteria;
            }
        }

        public int EditingId
        {
            get { return this.ViewState.Get("EditingId", 0); }
            set { this.ViewState.Set("EditingId", value); }
        }
        public GroupDto GroupDto
        {
            get
            {
                return new GroupDto()
                {
                    Name = this.uxNameField.Text,
                    Description = this.uxDescriptionField.Text,
                    IsEnabled = this.uxIsEnabledField.Checked,
                    Id = this.EditingId
                };
            }
            set
            {
                this.uxNameField.Text = value.Name;
                this.uxDescriptionField.Text = value.Description;
                this.uxIsEnabledField.Checked = value.IsEnabled;

                this.uxPopupUpdatePanel.Update();
            }
        }

        #endregion

        #region Methods

        public void HideDetailsPopup()
        {
            this.uxRolesList.PageIndex = 0;
            this.uxMembersList.PageIndex = 0;
            this.uxGroupMembersList.PageIndex = 0;
            this.uxGroupDetails.Hide();
        }

        public void ShowDetailsPopup()
        {
            this.uxGroupDetails.Show();
        }

        public void FillGroupMembers(EntitySearchResult<GroupMemberDto> groupMembers)
        {
            this.uxGroupMembersListSource.DataSource = groupMembers;
        }

        public void FillGroupsList(EntitySearchResult<GroupDto> entitySearchResult)
        {
            this.uxGroupsListSource.DataSource = entitySearchResult;
        }

        public void FillMembers(EntitySearchResult<MemberDto> members)
        {
            this.uxMembersListSource.DataSource = members;
        }

        public void FillRolesList(EntitySearchResult<Role> roles)
        {
            this.uxRolesListSource.DataSource = roles;
        }

        public IEnumerable<int> GetCurrentSelectedRoles()
        {
            return from row in this.uxRolesList.Rows.OfType<GridViewRow>()
                   where row.RowType == DataControlRowType.DataRow
                         && row.FindControl<CheckBox>("uxIsRoleCheckedField").Checked
                   select row.GetDataKeyValue<int>();
        }

        #endregion

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this._presenter.OnViewInitialized();
                SetPageDefaults();
            }
            this._presenter.OnViewLoaded();
        }

        protected void uxAdd_Click(object sender, EventArgs e)
        {
            this.Presenter.OnAddCommandClick();
        }

        protected void uxCancel_Click(object sender, EventArgs e)
        {
            this.Presenter.OnCancelCommandClick();
        }

        protected void uxGroupsList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Editing")
            {
                this.Presenter.OnEditCommand(e.CommandArgument.ConvertTo(0));
            }
            else if (e.CommandName == "Deleting")
            {
                this.Presenter.OnDeleteCommand(e.CommandArgument.ConvertTo(0));
            }
        }

        protected void uxGroupMembersListSource_Selecting(object sender, ObjectContainerDataSourceSelectingEventArgs e)
        {
            this.GroupMembersSearchCriteria.SortField = e.GetSortExpression();
            this.GroupMembersSearchCriteria.SortDirection = e.GetSortDirection();
            this.Presenter.OnLoadGroupMembersList();
        }

        protected void uxGroupsList_Selecting(object sender, ObjectContainerDataSourceSelectingEventArgs e)
        {
            this.SearchCriteria.SortField = e.GetSortExpression();
            this.SearchCriteria.SortDirection = e.GetSortDirection();
            this.Presenter.OnLoadGroupsList();
        }

        protected void uxMembersListSource_Selecting(object sender, ObjectContainerDataSourceSelectingEventArgs e)
        {
            this.MembersSearchCriteria.SortField = e.GetSortExpression();
            this.MembersSearchCriteria.SortDirection = e.GetSortDirection();
            this.Presenter.OnLoadMembersList();
        }

        protected void uxSearch_Click(object sender, EventArgs e)
        {
            this.Presenter.OnSearchClick();
        }

        protected void uxRolesListSource_Selecting(object sender, ObjectContainerDataSourceSelectingEventArgs e)
        {
            this.RolesSearchCriteria.SortField = e.GetSortExpression();
            this.RolesSearchCriteria.SortDirection = e.GetSortDirection();
            this.Presenter.OnLoadRolesList();
        }

        protected void uxMembersList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var uxMemberImage = e.Row.FindControl("uxMemberImage") as Image;
                var member = e.Row.DataItem as MemberDto;

                if (uxMemberImage != null && member != null)
                    uxMemberImage.ImageUrl = member.MemberTypeCode == GroupMemberType.User
                                                 ? "~/Images/userIco_16.png"
                                                 : "~/Images/groupIco_16.png";
            }
        }

        protected void uxNameFieldDublicationValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = this.Presenter.OnValidateGroupNameDublication(args.Value);
        }

        protected void uxOk_Click(object sender, EventArgs e)
        {
            this.Presenter.OnOkCommandClicked();
        }

        protected void uxRolesList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.FindControl<CheckBox>("uxIsRoleCheckedField").Checked =
                    this.Presenter.IsInGroup(((Role)e.Row.DataItem).Id);
            }
        }

        #endregion events

        #region Methods
        private void SetPageDefaults()
        {
            this.uxNameFieldRequiredValidator.FormatMessage("'Name'");
            this.uxNameFieldDublicationValidator.FormatMessage("'Name'");
            this.uxSearch.Focus();
        }
        #endregion
    }
}